package com.kestrel.space.core.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.github.pagehelper.PageHelper;
import com.kestrel.space.common.utils.Generator;
import com.kestrel.space.common.utils.LargePage;
import com.kestrel.space.core.mapper.CommentMapper;
import com.kestrel.space.core.model.Comment;
import com.kestrel.space.core.query.CommentQuery;
import com.kestrel.space.core.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * @author yebolin
 * @date 2024/8/23
 */
@Service
public class CommentServiceImpl implements CommentService {
    @Autowired
    private CommentMapper commentMapper;

    @Override
    public List<Comment> listContent(CommentQuery query, LargePage page) {
        if (page != null) {
            PageHelper.startPage(page.getPageNum(), page.getPageSize());
        }
        Comment comment = BeanUtil.copyProperties(query, Comment.class);
        return commentMapper.select(comment);
    }

    @Override
    public String saveOrUpdate(Comment comment) {
        String message = "插入成功";
        if (comment.getId() == null) {
            comment.setId(Generator.generateId());
            commentMapper.insert(comment);
        } else {
            message = "更新成功";
            commentMapper.updateByPrimaryKeySelective(comment);
        }
        return message;
    }

    @Override
    public String batchSaveOrUpdate(List<Comment> commentList) {
        String message = "批量插入成功";
        if (CollectionUtils.isEmpty(commentList)) {
            return "集合为空";
        }
        if(commentList.get(0).getId() == null){
            for (Comment comment : commentList) {
                comment.setId(Generator.generateId());
                commentMapper.insert(comment);
            }
        } else {
            message = "批量更新成功";
            for (Comment comment : commentList) {
                comment.setId(Generator.generateId());
                commentMapper.updateByPrimaryKey(comment);
            }
        }
        return message;
    }
}
